﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Web.Design;
using CMS.Core.Domain;
using System.Data;
using System.IO;

namespace CMS.Web.Reports
{
    class ReportHelper
    {
        #region Create Instance
        private static ReportHelper instance = null;
        public static ReportHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ReportHelper();
                }
                return instance;
            }
        }
        #endregion

        public void AddFormular(ReportDocument reportsource, string name, object value)
        {
            try
            {
                FormulaFieldDefinition objformular;
                objformular = reportsource.DataDefinition.FormulaFields[name] as FormulaFieldDefinition;
                objformular.Text = "'" + value + "'";
            }
            catch (Exception ex)
            {
                throw (ex);
            }

        }

        public void SetImage(string tableName, string imgpath, ReportDocument reportDocument)
        {
            DataTable dt = new DataTable(tableName);
            dt.Columns.Add(new DataColumn(tableName, typeof(byte[])));
            DataRow dr = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                byte[] value = br.ReadBytes((int)fs.Length);
                br.Close();
                fs.Close();

                dr = dt.NewRow();
                dr[tableName] = value;
            }
            catch
            {
                // Giá trị mặc định là Null nếu không đọc được ảnh
                dr[tableName] = DBNull.Value;
            }
            finally
            {
                dt.Rows.Add(dr);
            }

            reportDocument.Database.Tables[tableName].SetDataSource(dt);
        }
    }
}
